<template>
  <div>
    <el-dialog title="修改用户信息" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" v-model="selectedUser" style="text-align: left">
        <el-form-item
          label="用户名"
          label-width="120px"
          prop="username"
          :rules="rules.username"
        >
          <label>{{ selectedUser.username }}</label>
        </el-form-item>
        <el-form-item
          label="真实姓名"
          label-width="120px"
          prop="name"
          :rules="rules.name"
        >
          <el-input v-model="selectedUser.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="手机号"
          label-width="120px"
          prop="phone"
          :rules="rules.phone"
        >
          <el-input v-model="selectedUser.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px" prop="email">
          <el-input v-model="selectedUser.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" label-width="120px" prop="password">
          <el-button
            type="warning"
            @click="resetPassword(selectedUser.username)"
          >重置密码</el-button>
        </el-form-item>
        <el-form-item label="角色分配" label-width="120px" prop="roles">
          <el-checkbox-group v-model="selectedRolesIds">
            <el-checkbox v-for="(role, i) in roles" :key="i" :label="role.id">{{
              role.nameZh
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="onSubmit(selectedUser)"
        >确 定</el-button>
      </div>
    </el-dialog>
    <el-row style="margin: 18px 0px 0px 18px">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <!-- <el-breadcrumb-item :to="{ path: '/admin/dashboard' }" -->
        <el-breadcrumb-item>管理中心</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户信息</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>
    <bulk-registration @onSubmit="listUsers()" />
    <el-card style="margin: 18px 2%; width: 95%">
      <el-table
        ref="multipleTable"
        :data="users"
        stripe
        :default-sort="{ prop: 'id', order: 'ascending' }"
        style="width: 100%"
        :max-height="700"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="id" sortable width="100" />
        <el-table-column prop="username" label="用户名" fit />
        <el-table-column prop="name" label="真实姓名" fit />
        <el-table-column prop="phone" label="手机号" fit />
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip fit />
        <el-table-column prop="name_zh" label="角色权限" fit />
        <el-table-column label="状态" sortable width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="value => commitStatusChange(value, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editUser(scope.row)">
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleDelete(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <!-- <span class="demonstration"></span> -->
        <el-pagination
          :current-page="1"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <div style="margin: 20px 0 20px 0; float: left">
        <el-button @click="delchoose">批量删除</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import BulkRegistration from './BulkRegistration'
export default {
  inject: ['reload'],
  name: 'UserProfile',
  components: { BulkRegistration },
  data() {
    var checkUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'))
      }
      callback()
    }
    var checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('姓名不能为空'))
      }
      callback()
    }
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('电话不能为空'))
      }
      callback()
    }
    return {
      users: [],
      roles: [],
      dialogFormVisible: false,
      selectedUser: [],
      selectedRolesIds: [],
      // 批量选中的数据
      multipleSelection: [],
      // 保存批量选中后的数据
      delarr: [],
      delall: [],
      pageSize: 10,
      page: [],
      total: 12,
      rules: {
        username: [{ validator: checkUserName, trigger: 'blur' }],
        name: [{ validator: checkName, trigger: 'blur' }],
        phone: [{ validator: checkPhone, trigger: 'blur' }]
      }
    }
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 320
    }
  },

  // 在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
  mounted() {
    this.listUsers()
    this.listRoles()
    this.userNum()
    // this.listUsersPageChange();
  },
  methods: {
    // // 这是一个定时器
    // timer() {
    //   return setTimeout(() => {
    //     this.listUsers();
    //     this.listRoles();
    //     this.userNum();
    //   }, 5000);
    // },

    // 所有的用户信息（包括自己）
    listUsers() {
      var _this = this
      this.$axios.get('/api/admin/page/init').then(resp => {
        if (resp.status === 200) {
          _this.users = resp.data.data.datas
          // _this.total = resp.data.data.datas.length;
        }
      })
    },

    // 页码相关
    userNum() {
      var _this = this
      this.$axios.get('/api/admin/user').then(resp => {
        if (resp.status === 200) {
          _this.total = resp.data.data.length
        }
      })
    },

    // 分页
    current_change: function(currentPage) {
      this.currentPage = currentPage
    },

    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val
      console.log(this.pageSize)
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val
      console.log(val)
      const a = val
      // this.listUsersPageChange();
      this.$axios
        .get('/api/admin/page', {
          params: {
            page: this.page,
            pageSize: this.pageSize
          }
        })
        .then(resp => {
          console.log(resp)
          if (resp.status == 200) {
            // 分页数据回调
            this.users = resp.data.data.datas
            // this.total = res.data.result.datas.length;
          }
        })
        .catch(error => {
          this.$message.error('暂无数据')
        })
    },

    // 清空数据
    clear() {
      this.dataForm = {
        username: '',
        name: '',
        phone: '',
        email: '',
        roles: []
      }
    },

    // 获取所有的角色信息
    listRoles() {
      var _this = this
      this.$axios.get('/api/admin/role').then(resp => {
        if (resp.status === 200) {
          _this.roles = resp.data.data
        }
      })
    },
    // 改变用户状态
    commitStatusChange(value, user) {
      if (user.username !== 'admin') {
        this.$axios
          .put('/api/admin/user/status', {
            enabled: value,
            username: user.username
          })
          .then(resp => {
            if (resp.status === 200) {
              if (value) {
                this.$message.success('用户 [' + user.username + '] 已启用')
              } else {
                this.$message.success('用户 [' + user.username + '] 已禁用')
              }
            }
          })
      } else {
        user.enabled = true
        this.$message.error('不能禁用管理员账户')
      }
    },
    // 编辑
    onSubmit(user) {
      const _this = this
      // 根据视图绑定的角色 id 向后端传送角色信息
      const roles = []
      for (let i = 0; i < _this.selectedRolesIds.length; i++) {
        for (let j = 0; j < _this.roles.length; j++) {
          if (_this.selectedRolesIds[i] === _this.roles[j].id) {
            roles.push(_this.roles[j])
          }
        }
      }
      this.$axios
        .put('/api/admin/user', {
          username: user.username,
          name: user.name,
          phone: user.phone,
          email: user.email,
          roles: roles
        })
        .then(resp => {
          if (resp.status === 200) {
            // 修改角色后重新请求用户信息，实现视图更新
            this.listUsers()
            this.clear()
            this.$message.success(resp.data.data)
            this.reload()
          }
        })
        .catch(error => {
          this.$message.error(error.response.error)
          this.reload()
        })
    },
    // 编辑
    editUser(user) {
      this.dialogFormVisible = true
      this.selectedUser = user
      const roleIds = []
      for (let i = 0; i < user.roles.length; i++) {
        roleIds.push(user.roles[i].id)
      }
      this.selectedRolesIds = roleIds
    },

    // 单条删除
    handleDelete(index, row) {
      console.log(row.id)
      const _id = row.id
      this.$axios
        .delete('/admin/user/del', { data: { id: _id }})
        .then(resp => {
          // console.log(resp);
          if (resp.status === 200) {
            this.$message.success(resp.data.data)
            this.reload()
          }
        })
        .catch(error => {
          this.$message.error(error.response.error)
          this.reload()
        })
    },

    // 得到选中数据
    handleSelectionChange(val) {
      const a = (this.multipleSelection = val)
      // console.log(a);
      const resdata = JSON.parse(JSON.stringify(this.multipleSelection))
      // console.log("运行记录组件接到的数据", resdata);
      const b = Object.assign({}, a)
      this.delall = b
    },
    // 批量删除
    delchoose() {
      console.log('---------------------------')
      // 监听选中框的个数，定义变量承载选中的个数
      const length = this.multipleSelection.length
      console.log(length)
      if (length < 2) {
        this.$message.error('请至少选择两条数据')
      } else {
        for (let i = 0; i < length; i++) {
          // console.log(this.multipleSelection[i])
          this.delarr.push(this.multipleSelection[i].id)
          console.log(this.delarr[i])
        }
        // let resdata = JSON.parse(JSON.stringify(this.delarr));
        const resdata = JSON.stringify(this.delarr)
        console.log(resdata)
        this.$axios
          .delete('/admin/user/delMore', {
            params: {
              users: this.delarr
            },
            paramsSerializer: params => {
              return this.$qs.stringify(params, { indices: false })
            }
          })
          .then(resp => {
            // console.log(resp);
            if (resp.status === 200) {
              this.$message.success(resp.data.data)
              this.reload()
              console.log(resp)
            }
          })
          .catch(error => {
            this.$message.error(error.response.error)
            this.reload()
          })
      }
    },

    // 重置密码
    resetPassword(username) {
      this.$axios
        .put('/api/admin/user/password', {
          username: username
        })
        .then(resp => {
          if (resp.status === 200) {
            this.$message.success(resp.data.data)
            this.reload()
          }
        })
        .catch(error => {
          this.$message.error(error.response.error)
          this.reload()
        })
    }
  }
  // watch: {
  //   users(){
  //     this.timer();
  //   },
  //   roles(){
  //     this.timer();
  //   },
  // },
  // destroyed() {
  //   clearTimeout(this.timer);
  // }
}
</script>

<style scoped></style>
